var roleE9S59_T_I = {
    /** @param {Creep} creep **/
    run: function(creep) {
        // creep.say(creep.name);
        //creep.say(creep.memory.building);
        if(creep.store[RESOURCE_ENERGY] == 0){
            creep.memory.building = true;
        }
        else{
            creep.memory.building = false;
        }

        if(creep.memory.building == true){
            //creep.say(creep.memory.building);
            var targetsgo = creep.room.find(FIND_STRUCTURES, {
                filter: (structure) => {
                    return structure.structureType == STRUCTURE_STORAGE &&
                     structure.store.getUsedCapacity() > 0;
                }
            });
            if(targetsgo.length > 0) {
                if(creep.withdraw(targetsgo[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(targetsgo[0]);
                    //creep.say('运来');
                }
            }   

        }
        else{
            var targetsbuild = creep.room.find(FIND_CONSTRUCTION_SITES);
            //creep.say('运去3');
            var targets = creep.room.find(FIND_STRUCTURES, {
                filter: (structure) => {
                    return ((structure.structureType == STRUCTURE_EXTENSION ||
                            structure.structureType == STRUCTURE_SPAWN) && 
                            structure.store.getFreeCapacity(RESOURCE_ENERGY) > 0) ||
                            ((structure.structureType == STRUCTURE_TOWER) && 
                            structure.store.getFreeCapacity(RESOURCE_ENERGY) > 500);
                }
            });
            if(targets.length > 0) {
                //creep.say('运2去');
                    if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                        creep.moveTo(targets[0]);
                        //creep.say('运去');
                    }
                
            }
            else if(targetsbuild.length > 0){
                //建设           
                if(creep.build(targetsbuild[0]) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(targetsbuild[0], {reusePath:10});
                    //creep.say('建去');    //说话测试
                }
            }
            else{
                if(creep.transfer(Game.rooms['E9S59'].lookForAt('structure',38, 5)[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(Game.rooms['E9S59'].lookForAt('structure',38, 5)[0]);
                }
            }
        }
	}
};


module.exports = roleE9S59_T_I;